#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Common.Helpers/Class1 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       Class1
* 创建时间：  2025/5/22 16:42:04
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using System;
using System.Collections.Generic;
using ZXing;
using SkiaSharp;
using ZXing.QrCode;
using ZXing.Common;
using ZXing.SkiaSharp;

namespace SSPivot.Common.Helpers
{
    /// <summary>
    /// 二维码生成帮助类
    /// </summary>
    public class QrCodeHelper
    { 
        #region 二维码

        /// <summary>
        /// 生成二维码（HTML标签）
        /// </summary>
        /// <param name="content"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string GenQrCodeHtml(string content, int size, int margin, string logoPath = "")
        {
            return string.Format("<img src=\"data:image/png;base64,{0}\" alt=\"扫我\" />", GenQrCodeBase64(content, size,margin,logoPath));
        }

        /// <summary>
        /// 生成二维码（HTMLBase64）
        /// </summary>
        /// <param name="content"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string GenQrCodeBase64(string content, int size, int margin, string logoPath = "")
        {
            return Convert.ToBase64String(GenQrCode(content, size, margin, logoPath));
        }
          
        /// <summary>
        /// 生成二维码(带LOGO)
        /// </summary>
        /// <param name="content"></param>
        /// <param name="size"></param>
        /// <param name="margin"></param>
        /// <param name="logoPath"></param>
        /// <returns></returns>
        public static byte[] GenQrCode(string content, int size, int margin, string logoPath = "")
        {

            // 生成基础二维码
            var writer = new BarcodeWriter<SKBitmap>
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new QrCodeEncodingOptions
                {
                    Width = size,
                    Height = size,
                    Margin = margin,
                    CharacterSet = "UTF-8"
                }
            };
            var qrBitmap = writer.Write(content);

            if (logoPath.IsNotNullOrWhiteSpace())
            {
                // 加载Logo并合成
                using var logoStream = File.OpenRead(logoPath);
                using var logoBitmap = SKBitmap.Decode(logoStream);

                #region 旧代码

                //using var canvas = new SKCanvas(qrBitmap);
                //var logoSize = size / 5; // Logo占二维码1/5大小
                //var pos = (size - logoSize) / 2;

                //canvas.DrawBitmap(
                //    logoBitmap.Resize(
                //        new SKSizeI(logoSize, logoSize),
                //        SKFilterQuality.High),
                //    pos, pos);
                #endregion
                // 使用新版Resize API
                var sampling = new SKSamplingOptions(SKCubicResampler.Mitchell);
                using var resizedLogo = logoBitmap.Resize(
                    new SKSizeI(size / 5, size / 5),
                    sampling);

                // 合成图像
                using var canvas = new SKCanvas(qrBitmap);
                var pos = (size - resizedLogo.Width) / 2;
                canvas.DrawBitmap(resizedLogo, pos, pos);
                // 输出PNG
            }

            using var image = SKImage.FromBitmap(qrBitmap);
            using var data = image.Encode(SKEncodedImageFormat.Png, 100);
            return data.ToArray(); 
        }

        #endregion

        #region 条型码

        /// <summary>
        /// 生成条型码（HTML标签）
        /// </summary>
        /// <param name="content"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string GenBarCodeHtml(string content, int width, int height)
        {
            return string.Format("<img src=\"data:image/png;base64,{0}\" alt=\"扫我\" />", GenBarCodeBase64(content, width, height));
        }

        /// <summary>
        /// 生成条型码（HTMLBase64）
        /// </summary>
        /// <param name="content"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string GenBarCodeBase64(string content, int width, int height)
        {
            return Convert.ToBase64String(GenBarCode(content, width, height));
        }

        /// <summary>
        /// 生成条型码
        /// </summary>
        /// <param name="content"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static byte[] GenBarCode(string content, int width, int height,int margin=1)
        {
            var writer = new BarcodeWriter<SKBitmap>
            {
                Format = BarcodeFormat.CODE_128,
                Options = new EncodingOptions
                {
                    Width = width,
                    Height = height,
                    Margin = margin
                }
            };
            var barcode = writer.Write(content);
            using var image = SKImage.FromBitmap(barcode);
            using var data = image.Encode(SKEncodedImageFormat.Png, 100);
            return data.ToArray();
             
        }

        #endregion

        /// <summary>
        /// 读取二维码
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string ReadQrCode(byte[] file)
        {
            // 使用SKBitmap加载图像
            using var image = SKBitmap.Decode(file);
            
            // 配置BarcodeReader
            var reader = new BarcodeReader<SKBitmap>((image) =>new SKBitmapLuminanceSource(image))
            {
                Options = new DecodingOptions
                {
                    PossibleFormats = new List<BarcodeFormat>
                    {
                        BarcodeFormat.QR_CODE,   // 识别二维码
                        BarcodeFormat.CODE_128    // 识别Code 128条形码
                    },
                    TryHarder = true             // 提高识别率
                },
                AutoRotate = true                 // 自动旋转图像
            };
            
            var result = reader.Decode(image);
            return result?.Text ?? string.Empty;
        }
        /// <summary>
        /// 解析并标记二维码位置
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static QrcodePostion MarkPoster(byte[] file)
        {
            var result = new QrcodePostion();
            
            using var image = SKBitmap.Decode(file);
            result.Width = image.Width;
            result.Height = image.Height;

            var reader = new BarcodeReader<SKBitmap>((image) => new SKBitmapLuminanceSource(image))
            {
                Options = new DecodingOptions
                {
                    PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE },
                    TryHarder = true
                },
                AutoRotate = true
            };

            var qrcodeInfo = reader.Decode(image);
            if (qrcodeInfo != null && qrcodeInfo.ResultPoints != null && qrcodeInfo.ResultPoints.Length >= 3)
            {
                var points = qrcodeInfo.ResultPoints;
                result.X = (int)points[0].X;
                result.Y = (int)points[0].Y;
                result.QrcodeWidth = (int)Math.Abs(points[1].X - points[2].X);
                result.QrcodeHeight = (int)Math.Abs(points[0].Y - points[1].Y);
            }

            return result;
        }

    }

    /// <summary>
    /// 二维码位置
    /// </summary>
    public class QrcodePostion
    {
        /// <summary>
        /// 源图宽度
        /// </summary>
        public int Width { get; set; }

        /// <summary>
        /// 源图高度
        /// </summary>
        public int Height { get; set; }

        /// <summary>
        /// X轴
        /// </summary>
        public int X { get; set; }

        /// <summary>
        /// Y轴
        /// </summary>
        public int Y { get; set; }

        /// <summary>
        /// 二维码宽度
        /// </summary>
        public int QrcodeWidth { get; set; }

        /// <summary>
        /// 二维码高度
        /// </summary>
        public int QrcodeHeight { get; set; }
    }
}
